package jp.tf_web.httpserversample.http;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.util.Log;

public class HttpServer extends Thread {
	private final Context _context;
	private boolean _is_closed = false;
	private final String _ip_addr_str;
	private final int _port;
	private ServerSocket _server;
	private final ExecutorService _executor;

	public HttpServer(Context context,int port){
		super();
		this._context = context;
		this._ip_addr_str = this.getIPAddr();
		this._port = port;
		Log.d(this.getClass().getName(),"HttpServer init 1");
		this._executor = Executors.newFixedThreadPool(5);
		Log.d(this.getClass().getName(),"HttpServer init 2");
	}
	
	public String getPortStr(){
		return Integer.toString(this._port);
	}
	
	//ローカルIPアドレスを取得
	public String getIPAddrStr(){
		return this._ip_addr_str;
	}
	
	private String getIPAddr(){
	    Enumeration<NetworkInterface> interfaces = null;
		try {
			interfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if(interfaces != null){
		    while(interfaces.hasMoreElements()){
		        NetworkInterface network = interfaces.nextElement();
		        Enumeration<InetAddress> addresses = network.getInetAddresses();
		        while(addresses.hasMoreElements()){
		            String address = addresses.nextElement().getHostAddress();
		            if(!"127.0.0.1".equals(address) && !"0.0.0.0".equals(address)){
		                return address;
		            }
		        }
		    }
        }
	    return "127.0.0.1";
	}
	
	//開始
	public void start() {
		_is_closed = true;
		super.start();
	}
	
	//停止
	public void interrupt(){
		this._is_closed = false;
		this._executor.shutdown();
		//super.interrupt();
	}
	
	//メッセージ受信スレッド
	public void run() {
        try {
        	Socket socket;
            this._server=new ServerSocket();
            this._server.setReuseAddress(true);
            this._server.bind(new InetSocketAddress(this._ip_addr_str,this._port));

            while(_is_closed) {
                try {
                	Log.d(this.getClass().getName(),"accept");
                	socket = this._server.accept();
                	HttpServerWorker work = new HttpServerWorker(this._context,socket);
                	this._executor.execute(work);
                } catch (IOException e) {
                	//
                }
            }
        }
        catch (IOException e) {
            System.err.println(e);
        }
	}

}
